import Vue from 'vue'
import store from '@/store'
import VueRouter from 'vue-router'
const Layout = () => import('@/views/layout')
const Login = () => import('@/views/login')
const Home = () => import('@/views/layout/Home')
const QA = () => import('@/views/layout/QA')
const Video = () => import('@/views/layout/Video')
const User = () => import('@/views/layout/User')
const Edit = () => import('@/views/Edit')
const Search = () => import('@/views/search/search')
const Result = () => import('@/views/search/result')
const Detail = () => import('@/views/Article/detail')
const Chat = () => import('@/views/chat')

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        component: Home,
        meta: {
          isKeepAlive: true
        }
      },
      {
        path: 'qa',
        component: QA
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/user/edit',
    component: Edit
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: Result
  },
  {
    path: '/article/:id',
    component: Detail
  },
  {
    path: '/user/chat',
    component: Chat
  }
]

const router = new VueRouter({
  routes
})

const whiltList = ['/user', '/user/edit']
router.beforeEach((to, from, next) => {
  const token = store.state.user.token.token
  if (token) {
    return next()
  }
  if (!whiltList.includes(to.path)) {
    return next()
  }
  next({
    path: '/login',
    query: {
      back: to.path
    }
  })
})

export default router
